package org.redmagic.service.dao;

import java.util.List;

import org.redmagic.service.domain.Property;
import org.redmagic.service.utils.MongoProperties;
import org.redmagic.service.utils.MongoUtils;

import com.google.common.base.Optional;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;

public class MongoDbDao implements MagicDao {

	private final DBCollection properties;
	private final DBObject fields;
	
	public MongoDbDao(Mongo mongo, String databaseName, String collectionName) {		
		DB database = mongo.getDB(databaseName);
		this.properties = database.getCollection(collectionName);
		this.fields = new BasicDBObject(MongoProperties.ID, 0);
		this.fields.put(MongoProperties.VALUE_KEY, 1);
	}
	
	@Override
	public Optional<String> getProperty(String base, List<String> tags,	String user) {
		
		DBObject query = MongoUtils.getQuery(base, tags);
		System.out.println(query);
		DBObject dbResult = this.properties.findOne(query, fields);
		
		String value = null;
		if (dbResult != null) {
			value = (String) dbResult.get(MongoProperties.VALUE_KEY);
			this.properties.update(query, MongoUtils.getAccessObject(user));
		}
		
		return Optional.fromNullable(value);
	}

	@Override
	public boolean createProperty(Property createOrUpdateProperty, String user) {
		DBObject insertObject = MongoUtils.getInsertObject(createOrUpdateProperty, user);
		this.properties.insert(insertObject, WriteConcern.SAFE);
		return true;
	}

	@Override
	public boolean updateProperty(Property property, String user) {
		DBObject queryObject = MongoUtils.getQuery(property);
		DBObject updateObject = MongoUtils.getUpdateObject(property, user);
		
		System.out.println("QueryObject: " + queryObject);
		System.out.println("UpdateObject: " + updateObject);
		
		this.properties.update(queryObject, updateObject);
		return true;
	}
}
